#include<iostream>
#include<cstdlib>
#include <unistd.h>
#include <string>

bool GetQueryString(std::string &query_string) //获取需要的参数
{
    bool result = false;
    std::string method = getenv("METHOD");
    if(method == "GET")
    {
        //通过环境变量拿到GET方法后，照样通过环境变量拿到参数
        query_string = getenv("QUERY_STRING");
        result = true;
    }
    else if(method == "POST")
    {
        int content_length = atoi(getenv("CONTENT_LENGTH"));
        char c = 0;
        while(content_length)
        {
            read(0, &c, 1);
            query_string.push_back(c);
            content_length--;
        }
        result = true;
    }
    else //如果要支持其它方法就可以在这里继续拓展
    {
        result = false;
    }
    return result;
}

void CutString(std::string &in, const std::string &sep, std::string &out1, std::string &out2)
{
    auto pos = in.find(sep);
    if(std::string::npos != pos)
    {
        out1 = in.substr(0, pos);
        out2 = in.substr(pos+sep.size());
    }
}

int main()
{
    std::string query_string;
    GetQueryString(query_string); //a=100$b=200

    std::string str1;
    std::string str2;
    CutString(query_string, "&", str1, str2); //"a=100", "b=200"

    std::string name1;
    std::string value1;
    CutString(str1, "=", name1, value1); //"a", "100"

    std::string name2;
    std::string value2;
    CutString(str2, "=", name2, value2); //"b", "200"

    int x = atoi(value1.c_str());
    int y = atoi(value2.c_str());

    std::cout<<"<html>";
    std::cout<<"<head><meta charset=\"UTF-8\"></head>";
    std::cout<<"<body>";
    std::cout<<"<h3>"<<x<<" + "<<y<<" = "<<x+y<<"</h3>";
    std::cout<<"<h3>"<<x<<" - "<<y<<" = "<<x-y<<"</h3>";
    std::cout<<"<h3>"<<x<<" * "<<y<<" = "<<x*y<<"</h3>";
    std::cout<<"<h3>"<<x<<" / "<<y<<" = "<<x/y<<"</h3>"; //除0后cgi程序崩溃，属于异常退出
    std::cout<<"</body>";
    std::cout<<"</html>";

    return 0;
}